// api/order_api/order_ceate.go
package order_api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"math/rand"
	"muziai-server/api/ali_api"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/models/ctype"
	"muziai-server/utils/jwts"
	"muziai-server/utils/res"
	"time"
)

type OrderCreateRequest struct {
	PayType int8  `json:"payType" binding:"required,oneof=1"`          // 1 支付宝 2 wx
	Price   int64 `json:"price" binding:"required,oneof=100 500 1000"` //
}
type OrderCreateResponse struct {
	No     string `json:"no"`
	Price  int64  `json:"price"`
	PayUrl string `json:"payUrl"`
}

var PriceToScopeMap = map[int64]int64{
	100:  100,
	500:  600,
	1000: 2000,
}

func (OrderApi) OrderCreateView(c *gin.Context) {
	var cr OrderCreateRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailWithError(c, err)
		return
	}

	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.Claims)
	// 订单复用
	var order models.OrderModel
	err = global.DB.Take(&order,
		"user_id = ? and price = ? and pay_status = ? and pay_source = ?",
		claims.UserID, cr.Price, ctype.UnpaidPayStatus, cr.PayType,
	).Error
	if err == nil {
		// 订单复用
		res.OkWithData(c, OrderCreateResponse{
			No:     order.No,
			Price:  order.Price,
			PayUrl: order.PayUrl,
		})
		return
	}
	//创建订单号码
	var no = GenerateOrderNumber()
	//实例化ali接口进行付费操作
	api := ali_api.AliApi{}
	//调用aliapi
	payUrl := api.Pay(c, no, Int64ToStringWithDecimal(cr.Price/100))
	if payUrl == "" {
		res.FailWithMsg(c, "支付宝订单创建失败")
		return
	}
	// 创建订单
	order = models.OrderModel{
		UserID:    claims.UserID,
		No:        no,
		Price:     cr.Price,
		Scope:     PriceToScopeMap[cr.Price],
		PayStatus: ctype.UnpaidPayStatus,
		PaySource: cr.PayType,
		PayUrl:    payUrl,
	}

	err = global.DB.Create(&order).Error
	if err != nil {
		res.FailWithMsg(c, "订单创建失败")
		return
	}

	// 订单过期  redis的有序集合 zset 来实现 延迟队列
	orderExpire := global.Config.Aalipay.OrderExpire
	err = global.OrderDelayQueue.SendDelayMsg(no, time.Duration(orderExpire)*time.Minute) //该订单5分钟后，发送信息
	if err != nil {
		logrus.Error(err)
		res.FailWithMsg(c, "订单创建失败")
		return
	}

	// no_ 20240819 1724068597 765423
	res.OkWithData(c, OrderCreateResponse{
		No:     order.No,
		Price:  order.Price,
		PayUrl: order.PayUrl,
	})
	return

}

func GenerateOrderNumber() string {
	// 获取当前日期时间作为订单号的一部分
	currentTime := time.Now().Format("20060102150405")

	// 生成随机数作为订单号的一部分
	rand.Seed(time.Now().UnixNano())
	randomPart := fmt.Sprintf("%04d", rand.Intn(10000))

	// 构建订单号
	orderNumber := currentTime + randomPart

	return orderNumber
}

func Int64ToStringWithDecimal(value int64) string {
	return fmt.Sprintf("%d.00", value)
}
